//
//  BKPhoneCardsRecordViewController.m
//  bestkeep
//
//  Created by yons on 16/12/2.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKPhoneCardsRecordViewController.h"
#import "BKMainCommon.h"
#import "BKRechargeRecordCell.h"

@interface BKPhoneCardsRecordViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) NSMutableArray *modelArray;
@property (nonatomic, strong) NSString *currentPage;//当前页数
@property (nonatomic, strong) NSString *totalCount;//总记录数
@property (nonatomic, strong) NSString *totalPage;//总页数
@property (nonatomic, strong) NSMutableArray *monthArray;
@property (nonatomic, strong) NSMutableArray *monthRecordArr;
@property (nonatomic, assign) BOOL hasRecord;
@property (nonatomic, assign) NSInteger page_no;
@property (nonatomic, strong) UITableView *rechargeTable;

@end

@implementation BKPhoneCardsRecordViewController

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];

}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];

}

-(NSMutableArray *)monthRecordArr{
    if (_monthRecordArr == nil) {
        _monthRecordArr = [NSMutableArray array];
    }
    return _monthRecordArr;
}

-(NSMutableArray *)modelArray{
    if (_modelArray == nil) {
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

-(NSMutableArray *)monthArray{
    if (_monthArray == nil) {
        _monthArray = [NSMutableArray array];
    }
    return _monthArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = BKMainLocalizedString(@"BKPhoneCardsRecordTitle");
    self.view.backgroundColor = RGBACOLOR(242, 242, 242, 1);
    _page_no = 1;
    [self setupTableView];
    [self getRecharegRecordListWithPageNO:self.page_no];
    [self setupRefresh];
    [self refreshData];
}
-(void)setupRefresh{
    
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    _rechargeTable.mj_header = header;
    
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(updataMore)];
    footer.stateLabel.textColor = [UIColor lightGrayColor];
    footer.stateLabel.font = [UIFont systemFontOfSize:14];
    footer.arrowView.image = [UIImage imageNamed:@"BKGDPullDown"];
    UIActivityIndicatorView *loadingView = [footer valueForKeyPath:@"loadingView"];
    loadingView.hidesWhenStopped = YES;
    loadingView.color=RGB(42, 187, 155);
    [footer addSubview:loadingView];
    _rechargeTable.mj_footer = footer;

   
    _rechargeTable.mj_footer.automaticallyHidden = YES;
}

-(void)refreshData{
    
    if (_hasRecord == YES) {
        self.page_no = 1;
        [self.modelArray removeAllObjects];
        [self.monthArray removeAllObjects];
        [self.monthRecordArr removeAllObjects];
        [self getRecharegRecordListWithPageNO:1];
        MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(updataMore)];
        footer.stateLabel.textColor = [UIColor lightGrayColor];
        footer.stateLabel.font = [UIFont systemFontOfSize:14];
        footer.arrowView.image = [UIImage imageNamed:@"BKGDPullDown"];
        UIActivityIndicatorView *loadingView = [footer valueForKeyPath:@"loadingView"];
        loadingView.hidesWhenStopped = YES;
        loadingView.color=RGB(42, 187, 155);
        [footer addSubview:loadingView];
        _rechargeTable.mj_footer = footer;
        
        
        _rechargeTable.mj_footer.automaticallyHidden = YES;

        
    }else{
        [self.modelArray removeAllObjects];
        [self.monthArray removeAllObjects];
        [self.monthRecordArr removeAllObjects];
        [_rechargeTable reloadData];
        [_rechargeTable.mj_header endRefreshing];
    }
    
}

-(void)updataMore{
    
    if ([self.totalPage integerValue] > 0) {
        if (_page_no < [self.totalPage integerValue]){
            _page_no += 1;
            [self getRecharegRecordListWithPageNO:self.page_no];
        }else{
            [_rechargeTable.mj_footer endRefreshing];
            self.rechargeTable.mj_footer = nil;
            
        }
    }else{
        [_rechargeTable.mj_footer endRefreshing];
        self.rechargeTable.mj_footer = nil;
    }
}


-(void)getRecharegRecordListWithPageNO:(NSInteger)pageNumber{
    [BKIndicationView showInView:self.view];
    [BKMainCommon getPhoneCardsRecord:[NSString stringWithFormat:@"%ld", (long)pageNumber] myCallback:^(id obj, NSError *error) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenWidth-64)];
        view.backgroundColor = [UIColor clearColor];
        [self.view addSubview:view];
        
        
        if (error) {
            
//            [SVProgressHUD dismiss];
            view.hidden = YES;
            
            
        }else{
            NSLog(@"%@", obj);
            
            view.hidden = YES;
            if (obj) {
                NSDictionary *dic = obj;
                if ([[NSString stringWithFormat:@"%@", dic[@"totalCount"]] isEqualToString:@"0"]) {
                    [self.view addSubview:[self getViewWhenDataEndLoading]];
                }else{
                    
                    self.currentPage = [NSString stringWithFormat:@"%@", dic[@"currentPage"]];
                    self.totalCount = [NSString stringWithFormat:@"%@", dic[@"totalCount"]];
                    self.totalPage = [NSString stringWithFormat:@"%@", dic[@"totalPage"]];
                    NSArray *monthList = dic[@"monthList"];
                    for (NSDictionary *monthDic in monthList) {
                        
                        NSArray *orderList = monthDic[@"orderList"];
                        if (_monthArray.count > 0) {
                            if (![_monthArray.lastObject isEqualToString:monthDic[@"month"]]) {
                                [_monthArray addObject:monthDic[@"month"]];
                                [_monthRecordArr addObject:[NSString stringWithFormat:@"%ld", (long)orderList.count]];
                            }else{
                                
                                NSInteger lastCount = (long)([_monthRecordArr.lastObject integerValue] + orderList.count);
                                [_monthRecordArr removeLastObject];
                                [_monthRecordArr addObject:[NSString stringWithFormat:@"%ld", (long)lastCount]];
                            }
                        }else{
                            [_monthArray addObject:monthDic[@"month"]];
                            [_monthRecordArr addObject:[NSString stringWithFormat:@"%ld", (long)orderList.count]];
                        }
                        for (NSDictionary *dic in orderList) {
                            BKPhoneCardsModel *recordModel = [[BKPhoneCardsModel alloc] initWithDictionary:dic];
                            [_modelArray addObject:recordModel];
                        }
                    }
                    

                    
            
                    _hasRecord = YES;
                    if (_monthRecordArr.count != 0) {
                        [self.rechargeTable reloadData];
                    }
                    [_rechargeTable.mj_header endRefreshing];
                    [_rechargeTable.mj_footer endRefreshing];
                }
            }
        }
        [BKIndicationView dismiss];
    }];
}

- (UIView *)getViewWhenDataEndLoading {
    
    UIView *noMoreView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, self.view.frame.size.height)];
    noMoreView.backgroundColor = RGBACOLOR(242, 242, 242, 1);
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 90)];
    UILabel *promptLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
    [noMoreView addSubview:promptLabel];
    promptLabel.text = @"暂无充值记录";
    [promptLabel setTextAlignment:NSTextAlignmentCenter];
    promptLabel.font = [UIFont systemFontOfSize:16];
    promptLabel.backgroundColor = [UIColor clearColor];
    promptLabel.textColor = RGBACOLOR(182, 182, 182, 1);
    [noMoreView addSubview:imageView];
    
    CGPoint center = noMoreView.center;
    imageView.center = CGPointMake(center.x, center.y);
    promptLabel.center = CGPointMake(center.x, CGRectGetMaxY(imageView.frame)+30);
    imageView.image = [UIImage imageNamed:@"BKPhone_kongicon"];
    return noMoreView;
    
}

-(void)setupTableView{
    
    _rechargeTable = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _rechargeTable.delegate = self;
    _rechargeTable.dataSource = self;
    _rechargeTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_rechargeTable];
    [_rechargeTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top);
        make.left.equalTo(self.view.mas_left);
        make.bottom.equalTo(self.view.mas_bottom);
        make.right.equalTo(self.view.mas_right);
    }];
    
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return _monthArray.count;
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [_monthRecordArr[section] integerValue];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    BKRechargeRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RechargeRecord"];
    if (cell == nil) {
        cell = [[BKRechargeRecordCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"RechargeRecord"];
    }
    cell.userInteractionEnabled = NO;
    NSInteger index = 0;
    for (NSInteger i = 0; i < indexPath.section; i++) {
        if (_monthRecordArr.count != 0) {
            index += [_monthRecordArr[i] integerValue];
        }
    }
    if (_modelArray.count >= index + indexPath.row) {
        cell.recordModel = _modelArray[index + indexPath.row];
    }
    return cell;
}

//-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
//    return _monthArray[section];
//}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *sectionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 35)];
    sectionView.backgroundColor = RGBACOLOR(242, 242, 242, 1);
    UILabel *sectionLabel = [[UILabel alloc] initWithFrame:CGRectMake(ApplicationBackGauge, 0, ScreenWidth-2*ApplicationBackGauge, 35)];
    sectionLabel.center = sectionView.center;
    [sectionView addSubview:sectionLabel];
    sectionLabel.text = _monthArray[section];
    sectionLabel.textColor = HexColor(0x404040);
    sectionLabel.font = UIFontSmall;
    
    return sectionView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 70;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 35;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.0001;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
